<?php
namespace API\Controller;
use Common\Tool\Tool;
use API\Model\GoodsModel;
use API\Model\GoodsCartModel;
use API\Model\OrderModel;
use API\Model\OrderGoodsModel;
use API\Model\UserAddressModel;
use API\Model\UserModel;
use API\Model\OrderReturnGoodsModel;
/**
 * 订单控制器
 * @author 王强 
 */
class OrderController extends BaseController
{
    //0 未支付，1已支付，2，发货中，3已发货，4已收货，5退货,6退货审核中，7审核失败，8审核成功，退款中，9退款成功, 10：代发货，11待收货
    public function __construct()
    {
        parent::__construct();
        Tool::checkPost($_POST, (array)null, false, array('token')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        $this->isLogin();
    }
 
    //生成订单
    public function buildOrder()
    {
        Tool::checkPost($_POST, (array)null, false, array(
                'cart_id'
        )) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        
        $this->prompt($_POST, 'address_id', '请选择收货地址');
        //区分 来路
        if (!empty($_POST['guid']) && $_POST['guid'] == md5('goods'))
        {
            $this->buyNow();
        }
        
        // +----------------------------------------------------------------------
        // | 商品编号:商品数量 1:2,2:3,4:5【这里用不到】
        // +----------------------------------------------------------------------
        // | Tool::connect('parseString', $_POST['goods_id']);
        // +----------------------------------------------------------------------
        // | array('1' => 1,'2' => 2,'4' => 5 )
        // +----------------------------------------------------------------------
        // | $goods = Tool::joinString();
        // +----------------------------------------------------------------------
        $cartId = rtrim($_POST['cart_id'], ',');
        //查询商品信息
        $goodsData = GoodsCartModel::getInition()->getGoodCartById(array(
            'field' => 'goods_id,goods_num,price_new as goods_price,fanli_jifen',
            'where' => array('id' => array('in',$cartId))
        ));
        
        $this->prompt($goodsData, null, '购物车不存在', false);
        //连接字符串工具
        Tool::connect('parseString');
        $status = GoodsModel::getInitation()->isReduce($goodsData);
        $this->prompt($status, null, '订单生成失败，库存不足');
//         showData($goodsData, 1);
        //计算总价
        Tool::connect('ArrayChildren');
       
        $sum = Tool::sumByArray($goodsData);
        $_POST['user_id']   = $_SESSION['userId'];
        
        $_POST['price_sum'] = $sum;
        Tool::connect('Token');
        $insertOrderId = OrderModel::getInitation()->add($_POST);
        
        $this->prompt($insertOrderId, null, '生成订单失败');
        
        foreach ($goodsData as $key => &$value)
        {
            $value['order_id'] = $insertOrderId;
        }
        
        //插入订单数量表
        $insertId = OrderGoodsModel::getInitnation()->addAll($goodsData);
        
        $this->prompt($insertId, null, '生成订单失败');
        
        //清空指定购物车商品
        
        $status = GoodsCartModel::getInition()->delete(array(
            'where' => array('id' => array('in', $cartId))
        ));
       
        $this->prompt($status, null, '生成订单失败');
        //减少库存
        $isSuccess = GoodsModel::getInitation()->reduceAmount($goodsData);
        
        $data = array('order' => $insertOrderId, 'price_sum' => $sum);
        $this->updateClient($data, '订单生成');
    }
    
    /**
     * 立即购买 
     */
    public function buyNow()
    {
        Tool::checkPost($_POST, array('is_numeric' => array('cart_id','goods_num')), true, array('cart_id','goods_num')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        $_POST['goods_id'] = $_POST['cart_id'];
        unset($_POST['cart_id']);
        $this->prompt($_POST, 'address_id', '请选择收货地址');
        
        //获取商品信息
        $goods = GoodsModel::getInitation()->getGoodsById(array(
            'field' => 'id as goods_id,price_new as goods_price,fanli_jifen',
            'where' => array('id' => $_POST['goods_id']),
        ), 'select');
        $this->prompt($goods, null, '不存在此商品', false);
        
        //库存是否可减
        Tool::connect('parseString');
        Tool::isSetDefaultValue($goods[0], array('goods_num'), $_POST['goods_num']);
        $status = GoodsModel::getInitation()->isReduce($goods);
        $this->prompt($status, null, '订单生成失败，库存不足');
        
        //计算总价
        Tool::connect('ArrayChildren');
         
        $sum = Tool::buyNowMonery($goods, $_POST['goods_num']);
        
        $_POST['user_id']   = $_SESSION['userId'];
        
        $_POST['price_sum'] = $sum;
        Tool::connect('Token');
        $insertOrderId = OrderModel::getInitation()->add($_POST);
        
        $this->prompt($insertOrderId, null, '生成订单失败');
        $receive = array();
        Tool::connect('ArrayParse')->oneArray($receive, $goods);
      
//        
        $receive['order_id'] = $insertOrderId;
        $insertId = OrderGoodsModel::getInitnation()->add(array_merge($receive, $_POST));
        $this->prompt($insertId, null, '生成订单失败');
        //减少库存
        $isSuccess = GoodsModel::getInitation()->reduceAmount($goods);
        $data = array('order' => $insertOrderId, 'price_sum' => $sum);
        $this->updateClient($data, '订单生成');
    }
    /**
     * 结算页面 【购物车到结算】
     */
    public function settlement()
    {
        //查询购物车信息
        Tool::checkPost($_POST, (array)null, false, array(
            'cart_id'
        )) ? true : $this->ajaxReturnData(null, '400', '参数错误');
      
        //收货人之地
        $address = UserAddressModel::getInitation()->getDefaultByUser();
        
        $cartId = rtrim($_POST['cart_id'], ',');
        //查询购物车信息
        $goodsData = GoodsCartModel::getInition()->getGoodCartById(array(
            'field' => 'id as cart_id,goods_id,goods_num,price_new,fanli_jifen',
            'where' => array('id' => array('in',$cartId))
        ));
      
        $this->prompt($goodsData, null, '购物车不存在', false);
        //传递给商品
        Tool::connect('parseString');
        $goodsData = GoodsModel::getInitation()->getGoodsNameById($goodsData, 'id as goods_id,pic_url,title,taocan as taocan_name,price_old', array('pic_url','title','taocan_name','price_old'));
        //反序列化套餐
        $goodsData = Tool::command($goodsData);
        $data[]['goods'] = $goodsData;
        $user = UserModel::getInistnation()->getUserInfoById('add_jf_currency,add_jf_limit', 'select');
        $data[]['address']= $address ;
        $data[]['user']   = $user;
        $this->updateClient($data, '操作');
    }
    
    /**
     * 立即购买到结算 
     */
    public function buyNowSettlement()
    {
        //查询购物车信息
        Tool::checkPost($_POST, array('is_numeric' => array('goods_id', 'goods_num')), false, array(
            'goods_id'
        )) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        
        //收货人之地
        $address = UserAddressModel::getInitation()->getDefaultByUser();
        //获取商品信息
        $goods = GoodsModel::getInitation()->getGoodsById(array(
            'field' => 'id as goods_id,price_new,price_old,fanli_jifen,pic_url, title, taocan',
            'where' => array('id' => $_POST['goods_id']),
        ), 'find');
        //获取积分
        $this->prompt($goods, null, '不存在此商品', false);
        $user = UserModel::getInistnation()->getUserInfoById('add_jf_currency,add_jf_limit','select');
        
        $goods['goods_num'] = $_POST['goods_num'];
        $goods['taocan']    = unserialize($goods['taocan']);
        $goods['cart_id']   = $goods['goods_id'];
        
        $data[]['goods'][] = $goods;
        
        $data[]['address'] = $address;
        $data[]['guid']    = md5('goods');
        $data[]['user']    = $user;
        $this->updateClient($data, '操作');
    }
    
    // 订单管理(全部)
    public function orderList()
    {
        $orderData = $this->getOrder(array($_SESSION['userId']));
        
        $this->updateClient($orderData, '操作');
    }
   
    /**
     * 辅助方法 
     */
    private function getOrder(array $value, $where = null)
    {
        $order = OrderModel::getInitation()->getOrderByUser($value, $where);
        $this->prompt($order, null, '没有订单', false);
        
        Tool::connect('parseString');
        //传递给子表
        $orderGoods = OrderGoodsModel::getInitnation()->getGoodsInfoByOrder($order);
        
        //传递给商品表
        $goods  = GoodsModel::getInitation()->getGoodsByChildrenOrderData($orderGoods);
        $this->prompt($goods, null, '意外错误，很抱歉', false);
        
        //组合数据
        
        $orderData = Tool::parseTwoArray($order, $goods, 'order_id', array('goods'));
        
        return $orderData;
    }

    // 订单管理(待付款)
    public function  paymentList()
    {
        $data = $this->getOrder(array($_SESSION['userId'], 0), ' and order_status ="%s"');
       
        $this->updateClient($data, '操作');
    }
   
    // 订单管理(待收货)
    public function  receiptGoods()
    {
        
        $data = $this->getOrder(array($_SESSION['userId']), ' and order_status in(1,2,3,11,10)');
        $this->updateClient($data, '操作');
    }
    
    // 订单管理(待评价)
    public function  paymentsWaite()
    {
        $data = $this->getOrder(array($_SESSION['userId'], 0), ' and comment_status ="%s"');
         
        $this->updateClient($data, '操作');
    }
    // -1:取消订单,0 未支付，1已支付，2，发货中，3已发货，4已收货，5退货审核中，6审核失败，7审核成功，8退款中，9退款成功, 10：代发货，11待收货
    // 订单管理(待完成)
    public function paymentsOk()
    {
        $data = $this->getOrder(array($_SESSION['userId'], OrderModel::ReceivedGoods), ' and order_status ="%s"');
         
        $this->updateClient($data, '操作');
    }
    
    // 取消订单
    public function  cancelOrder()
    {
        Tool::checkPost($_POST, array('is_numeric' => array('orders_num')), true, array('orders_num')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
        
        //获取订单状态
        $this->getOrderStatus($_POST['orders_num'], OrderModel::NotPaid);
        
        //获取商品信息
        $goods = OrderGoodsModel::getInitnation()->getGoodsIdByOrderId($_POST['orders_num'], 'goods_id,goods_num');
       
        $this->prompt($goods, null, '订单错误', false);
        
        //整理库存
        $status = GoodsModel::getInitation()->updateStock($goods);
        
        $status = OrderModel::getInitation()->save(array(
            'order_status' => OrderModel::CancellationOfOrder,
        ), array('where' => array('id' => $_POST['orders_num'])));
        
        $this->updateClient($status, '操作', true);
    }
    
    
    //获取订单状态
    private function getOrderStatus($orderId, $statusValidata)
    {
        $status =  OrderModel::getInitation()->getOrderStatusByUser($orderId);
        // 查找这个订单是不是待收获
        if ($status != $statusValidata)
        {
            $this->prompt(null, null, '订单状态有误');
        }
        
        return true;
    }
    
    //退货中
    public function tuiHuoStatus()
    {
        $data = $this->getOrder(array($_SESSION['userId']), 
            ' and order_status in('.'"'.OrderModel::ReturnAudit.'"'.','.'"'.OrderModel::AuditFalse.'"'.','.'"'.OrderModel::AuditSuccess.'"'.')'
        );
         
        $this->updateClient($data, '操作');
    }
    
    // 确认收货
    public function confirm()
    {
        Tool::checkPost($_POST, array('is_numeric' => array('orders_num')), true, array('orders_num')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
    
        //获取订单状态
        $status =  OrderModel::getInitation()->getOrderStatusByUser($_POST['orders_num']);
        // 查找这个订单是不是待收获1,2,3,11,10
        
        $id = OrderModel::ReceiptOfGoods .','. OrderModel::YesPaid .','. OrderModel::InDelivery.','.OrderModel::AlreadyShipped;
        if (false === strpos($id, $status))
        {
           $this->prompt(null, null, '订单状态有误'); 
        }
        
        //获取商品编号
        $goods = OrderGoodsModel::getInitnation()->getGoodsIdByOrderId($_POST['orders_num']);
        
        //连接工具
        Tool::connect('parseString');
        $goosId = Tool::characterJoin($goods);
        //传递商品表
        $inter = GoodsModel::getInitation()->getGoodsById(array(
            'field' => 'fanli_jifen',
            'where' =>'id in ('.$goosId.')'
        ), 'select');
        
        $this->prompt($inter, null, '订单错误', false);
      
        // 积分相加
        Tool::connect('ArrayChildren');
        $integral = Tool::computationalIntegral($inter);
        //积分相加
        $status = UserModel::getInistnation()->addUserData($integral);
        
        $status = OrderModel::getInitation()->save(array(
                'order_status' => OrderModel::ReceivedGoods,
        ), array('where' => array('id' => $_POST['orders_num'])));
        $this->updateClient($status, '操作', true);
    }
    
    // 退货
    public function  tuihuo()
    {
        Tool::checkPost($_POST, array('is_numeric'=> array('order_id')), true , array('order_id', 'tuihuo_case')) ? true : $this->ajaxReturnData(null, '400', '参数错误');
      
        //获取订单状态
        $status = OrderModel::getInitation()->getOrderStatusByUser($_POST['order_id']);
        
        $status != OrderModel::ReceivedGoods ? : $this->prompt(null, null, '不支持退货，很抱歉');
        //插入退货理由表
        
        $status = OrderReturnGoodsModel::getInitation()->add($_POST);
        
        $status = OrderModel::getInitation()->save(array(
            'order_status' => OrderModel::ReturnAudit,
        ), array('where' => array('id' => $_POST['order_id'])));
        $this->updateClient($status, '退货审核中，操作', true);
        
    }
}